//
//  ChatPurevoiceRightcell.swift
//  app_rn_frontend
//
//  Created by wanghui on 2018/5/31.
//  Copyright © 2018年 Facebook. All rights reserved.
//

import UIKit
import Kingfisher

class ChatPurevoiceRightcell: ChatBaseCell {
    var playing = false
    
    @IBOutlet weak var durationLabel: UILabel!
    @IBOutlet weak var imgtopConstraint: NSLayoutConstraint!
    @IBOutlet weak var bgtopConstraint: NSLayoutConstraint!
    @IBOutlet weak var avatar: UIImageView!
    @IBOutlet weak var createTimelabel: WHLabel!
    @IBOutlet weak var namelabel: UILabel!
    @IBOutlet weak var voicebtn: UIButton!
    @IBOutlet weak var bgimg: UIImageView!
    @IBOutlet weak var voicebtnleftconstraint: NSLayoutConstraint!
    
    @IBOutlet weak var activityindicator: UIActivityIndicatorView!
    @IBOutlet weak var sendfailureBtn: UIButton!
    
    @IBOutlet weak var unreadDotView: UIView!
    @IBOutlet weak var minispaceConstraint: NSLayoutConstraint!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        
        self.createTimelabel.paddingLeft = 5
        self.createTimelabel.paddingRight = 5
        self.createTimelabel.layer.cornerRadius = 5
        self.createTimelabel.layer.masksToBounds = true
        
        voicebtn.addTarget(self, action: #selector(playAudio(_:)), for: .touchUpInside)
        voicebtn.setImage(#imageLiteral(resourceName:"message_voice_receiver_normal"), for: .normal)
        //        voiceBtn.layer.borderColor = UIColor(red: 0.78, green: 0.78, blue: 0.80, alpha: 1.00).cgColor
        //        voiceBtn.layer.borderWidth = 1
        voicebtn.imageView?.animationDuration = 1
        voicebtn.adjustsImageWhenHighlighted = false
        voicebtn.setImage(#imageLiteral(resourceName:"message_voice_sender_normal"), for: .normal)
        voicebtn.imageView?.animationImages = [
            #imageLiteral(resourceName:"message_voice_sender_playing_1"),
            #imageLiteral(resourceName:"message_voice_sender_playing_2"),
            #imageLiteral(resourceName:"message_voice_sender_playing_3")
        ]
        voicebtn.contentHorizontalAlignment = .right
        voicebtn.imageEdgeInsets = UIEdgeInsets(top: -6, left: 0, bottom: 0, right: 0)
        //        self.unreadDotView.layer.cornerRadius = self.unreadDotView.width/2
        self.unreadDotView.layer.cornerRadius = 3
        self.unreadDotView.layer.masksToBounds = true
        self.selectionStyle = UITableViewCell.SelectionStyle.none
        
        self.avatar.isUserInteractionEnabled = true
        let tapAvatar = UITapGestureRecognizer.init(target: self, action: #selector(tapSelector))
        self.avatar.addGestureRecognizer(tapAvatar)
        let resend = UITapGestureRecognizer.init(target: self, action: #selector(resendMsg))
        self.sendfailureBtn.addGestureRecognizer(resend)
        self.bgimg.isUserInteractionEnabled = true
        let tapBg = UITapGestureRecognizer.init(target: self, action: #selector(playAudio))
        self.bgimg.addGestureRecognizer(tapBg)
        
        // 注册通知
        // 音频播放完毕
        NotificationCenter.default.addObserver(self, selector: #selector(audioPlayBegin(_:)), name: NSNotification.Name(rawValue: noteChatMsgAudioPlayBegin), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(audioPlayEnd(_:)), name: NSNotification.Name(rawValue: noteChatMsgAudioPlayEnd), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(audioPlayInterrupted(_:)), name: NSNotification.Name(rawValue: noteChatMsgAudioPlayInterrupted), object: nil)
    }
    
    //长按头像实现@功能
    @objc func avatarAddLongPress() {
        let longPressGes = UILongPressGestureRecognizer.init(target: self, action: #selector(avatarLongPress(_:)))
        longPressGes.minimumPressDuration = 0.5
        
        longPressGes.allowableMovement = 30
        self.avatar.isUserInteractionEnabled = true
        self.avatar.addGestureRecognizer(longPressGes)
    }
    
    @objc func avatarLongPress(_ longPressGest:UILongPressGestureRecognizer) {
        if longPressGest.state == UIGestureRecognizer.State.began {
            //长按手势添加@
            self.delegate?.addAtInTextviewDelegate(msg: model)
        }else {
            
        }
    }
    
    @objc func tapSelector() {
        print("点击了头像")
    }
    
    
    @objc func resendMsg() {
        self.model.status = .pending
        self.layoutSubviews()
        self.delegate?.resend(self.model,cell:self)
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
    override func setup(model: ChatMessage) {
        super.setup(model: model)
        if let avatar = model.avatar {
            self.avatar.kf.setImage(with: KF.ImageResource(downloadURL: Common.avatarUrl(avatar) ?? URL(string: "localhost")!), placeholder: #imageLiteral(resourceName:"defaultAvatar"),options: [.processor(CryptorProcessor())])
        } else {
            self.avatar.image = #imageLiteral(resourceName:"defaultAvatar")
        }
        self.createTimelabel.isHidden = !model.showTimeLabel
        self.createTimelabel.text = model.timeStr
        self.namelabel.text = model.fromName
        if model.status == .pending {
            self.activityindicator.isHidden = false
            self.activityindicator.startAnimating()
        } else {
            self.activityindicator.isHidden = true
            self.activityindicator.stopAnimating()
        }
        self.sendfailureBtn.isHidden = !(model.status == .error)
        self.durationLabel.isHidden = (model.status != .success)
        self.imgtopConstraint.constant = self.createTimelabel.isHidden == true ? 8: 40
        
        self.durationLabel.text = "\(Int(ceil(model.audioDuration ?? 0)))\""
        var voiceWidth = 50 + 130 * CGFloat(model.audioDuration ?? 0) / 60
        if voiceWidth > 200 {
            voiceWidth = 200
        }
        self.minispaceConstraint.constant = voiceWidth
        self.unreadDotView.isHidden = model.read
        
        //        self.namelabel.isHidden = true
        //        self.bgtopConstraint.constant = cell.namelabel.isHidden == true ? 0 : 18
        if model.chatType == .p2p {
            bgtopConstraint.constant = 0
            namelabel.isHidden = true
        }
    }
    
    override func updateUI() {
        super.updateUI()
        DispatchQueue.main.async {
            if self.model.status == .pending {
                self.activityindicator.isHidden = false
                self.activityindicator.startAnimating()
            } else {
                self.activityindicator.isHidden = true
                self.activityindicator.stopAnimating()
            }
            self.sendfailureBtn.isHidden = !(self.model.status == .error)
            self.durationLabel.isHidden = (self.model.status != .success)
        }
    }
}


extension ChatPurevoiceRightcell {
    // MARK: 播放录音
    @objc func playAudio(_ btn: UIButton) {
        do {
            if !playing {
                self.resetAudioAnimation()
                playing = true
                AudioRecordUtils.instance.stopPlay()  //如果有其他的在播放，先停止其他的播放
                try AudioRecordUtils.instance.startPlaying(model: model)
                voicebtn.imageView?.startAnimating()
                
            } else {
                playing = false
                AudioRecordUtils.instance.stopPlay()
                voicebtn.imageView?.stopAnimating()
                
            }
        }catch {
            playing = false
            voicebtn.imageView?.stopAnimating()
        }
    }
    
    // MARK: 重置音频按钮动画(关闭动画)
    fileprivate func resetAudioAnimation() {
        voicebtn.imageView?.stopAnimating()
    }
    
    @objc func audioPlayBegin(_ note:Notification){
        playing = true
        voicebtn.imageView?.startAnimating()
    }
    @objc fileprivate func audioPlayEnd(_ note: Notification) {
        playing = false
        self.resetAudioAnimation()
    }
    @objc func audioPlayInterrupted(_ note:Notification){
        playing = false
        self.resetAudioAnimation()
    }
}
